﻿<template>
    <el-switch v-model="currentValue"
               :activeColor="activeColor"
               :inactiveColor="inactiveColor"
               :disabled="disabled"
               @change="change"></el-switch>
</template>

<script>
export default {
  name: 'form-switch',
  props: {
    value: [String, Boolean, Number],
    disabled: {
      type: Boolean
    },
    activeColor: String,
    inactiveColor: String,
    // 转换值方法
    convertValue: {
      type: Function,
      default: function (val) {
        return val
      }
    },
    // 反转转换值方法
    reverseValue: {
      type: Function,
      default: function (val) {
        return val
      }
    }
  },
  data () {
    return {
      currentValue: null
    }
  },
  watch: {
    value (newVal) {
      this.currentValue = this.myValue()
    },
    currentValue (newVal) {
      this.$emit('input', this.reverseValue(newVal))
    }
  },
  methods: {
    myValue () {
      let value = this.value || null

      switch (Object.prototype.toString.call(value)) {
        case '[object Boolean]':
          value = this.value
          break
        case '[object Undefined]':
        case '[object Null]':
          value = false
          break
        default:
          value = this.convertValue(this.value)
          break
      }

      return value
    },
    change (newVal) {
      this.$emit('change', newVal)
    }
  },
  created () {
    this.currentValue = this.myValue()
  }
}
</script>
